/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.impl.thread;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.paoding.rose.web.impl.module.Module;
import net.paoding.rose.web.var.PrivateVar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.util.WebUtils;

/**
 * 
 * @author qieqie.wang@paoding.net
 * 
 */
public class ModuleLocator {

	private Log logger = LogFactory.getLog(ModuleLocator.class);

	private ArrayList<ModuleInvocation> moduleInvocations = new ArrayList<ModuleInvocation>();

	public ModuleLocator(List<Module> modules) {
		init(modules);
		Collections.sort(moduleInvocations);
	}

	protected void init(List<Module> modules) {
		for (int i = 0; i < modules.size(); i++) {
			Module module = modules.get(i);
			this.moduleInvocations.add(new ModuleInvocation(module));
		}
	}

	public ModuleInvocation getModuleInvocation(String modulePath) throws IOException {
		for (ModuleInvocation invocation : moduleInvocations) {
			if (invocation.getModule().getPath().equals(modulePath)) {
				return invocation;
			}
		}
		return null;
	}

	public ModuleInvocation locate(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String uri = request.getRequestURI();
		if (WebUtils.isIncludeRequest(request)) {
			uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
		}
		String ctxpath = request.getContextPath();
		//
		String pathInfo; // 去除ctxpath的URI部分
		if (ctxpath.length() <= 1) {
			pathInfo = uri;
		} else {
			pathInfo = uri.substring(ctxpath.length());
		}

		ModuleInvocation moduleInvocation = null;
		for (ModuleInvocation invocation : moduleInvocations) {
			if (pathInfo.startsWith(invocation.getModule().getPath())) {
				moduleInvocation = invocation;
				break;
			}
		}

		// module
		if (moduleInvocation != null) {
			String modulePath = moduleInvocation.getModule().getPath();
			Path path = new Path(uri, ctxpath, pathInfo, modulePath);
			if (logger.isDebugEnabled()) {
				logger.debug("path[" + path + "]");
			}
			PrivateVar.invocationVariables().setPath(path);
		}
		return moduleInvocation;
	}

}
